package com.lee.lease.web.app.service.service.impl;



import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lee.lease.common.custom.exception.LeaseException;
import com.lee.lease.common.result.ResultCodeEnum;
import com.lee.lease.common.util.JwtUtil;
import com.lee.lease.common.util.VerifyCodeUtil;
import com.lee.lease.model.entity.UserInfo;
import com.lee.lease.model.enums.BaseStatus;
import com.lee.lease.model.enums.RedisConstant;
import com.lee.lease.web.app.mapper.UserInfoMapper;
import com.lee.lease.web.app.service.SmsService;
import com.lee.lease.web.app.vo.login.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private Client client;

    @Autowired
    private UserInfoMapper mapper;

    @Override
    public Integer getCode(String phone) {
        //判断收否输入手机号
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        //判断redis中目前有没有这个key,并判断是否达到频繁发送的情况
        Boolean hasKey = redisTemplate.hasKey(phone);
        if (hasKey) {
            //剩余时间
            Long expire = redisTemplate.getExpire(phone, TimeUnit.SECONDS);
            if((RedisConstant.APP_LOGIN_CODE_TTL_SEC.getTime()-expire) < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC.getTime()){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        //创建一个随机验证码,参数为验证码的位数,然后发送
        String code = VerifyCodeUtil.getVerifyCode(6);
//        sendCode(phone, code);
        redisTemplate.opsForValue().set(phone,code,300, TimeUnit.SECONDS);
        return null;
    }



    @Override
    public String login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        if (StringUtils.hasText(phone)) {
            String loginCode = loginVo.getCode();
            //判断手机号是否正确

            //判断是否输入验证码
            if (!StringUtils.hasText(loginCode)) {
                throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
            }
            //判断验证码是否过期
            String code = redisTemplate.opsForValue().get(loginVo.getPhone());
            if (!StringUtils.hasText(code)) {
                throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
            }
            //判断验证码收否正确
            if (!loginCode.equals(code)) {
                throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
            }
            //判断用户是否存在,不存在则创建用户
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserInfo::getPhone,phone);
            UserInfo userInfo = mapper.selectOne(queryWrapper);
            if (userInfo==null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                mapper.insert(userInfo);
            }

            //判断用户状态是否禁用
            if (BaseStatus.DISABLE.equals(userInfo.getStatus())){
                throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
            }
            String token = JwtUtil.createToken(userInfo.getId(),userInfo.getPhone());

            return token;
        }else {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
    }

    @Override
    public void sendCode(String phone, String code) {
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}\n");
        try {
            client.sendSms(smsRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
